package com.kdtech.analyse.Bbs;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.DoMainUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.NumberUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.kdtech.analyse.AnalyseNews;
import com.kdtech.analyse.Bbs.common.BbsAnalyseDiscuz;
import com.kdtech.crawler.CrawlHTML;

import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;

public class PdxxgBbsAnalyse implements AnalyseNews  {

	public boolean isDetailPage(String url) {
		url = UrlArgumentTop.FromatUrl(url);
		String[] regex = {
				"http://www.pdxxg.com/bbs/[0-9]*.html",
				};
		return RegexUtils.matchAny(url, regex);
	}

	public NewsMeta parserHtml(UrlMeta urlMeta) {

		if (urlMeta.getHtml() == null) {
		}
		String htmltxt = urlMeta.getHtml();
		String url = urlMeta.getUrl();

		String title = null;
		String content = null;
		Long date = null;
		Integer commnetNum = null;
		Integer clickNum = null;
		String updateUrl = url;
		String author=null;
		Document doc = Jsoup.parse(htmltxt);
		NewsMeta news = new NewsMeta();


		title = doc.select("title").text();
		if(title.contains("-")){
			title = StringUtils.substringBefore(title, "-");
		}

		Element firstDiv = doc.select("div.x_list").first();
		if (firstDiv!=null){
			author = firstDiv.select("div.l").text();
			author = StringUtils.substringBetween(author, "：", "积分");
			date = DateUtils.matchDate(firstDiv.select("div.sj").text());
			content = HtmlCleaner.getContentHtml(url,  firstDiv.select("div.nr"));
		}

		String commTxt = doc.select("h1#x_bt").text();
		if(StringUtils.isNotBlank(commTxt)){
			clickNum = NumberUtils.matchNumber(StringUtils.substringAfter(commTxt, "查看"));
		}

		news.setUrl(url);
		news.setAuthor(author);
		news.setTitle(StringUtils.trimSpace(title));
		news.setCommentNum(commnetNum);
		news.setClickNum(clickNum);
		news.setContent(StringUtils.trimSpace(content));
		news.setDate(date);
		news.setUpdateUrl(updateUrl);
		return news;

	}

	public NewsMeta Update(NewsMeta meta) {
		String url = meta.getUpdateUrl();
		if (StringUtils.isNotBlank(url)){
			UrlMeta urlMeta = CrawlHTML.responseToURL(url);
			return parserHtml(urlMeta);
		}
		return null;
	}

	public boolean isNeedUpdate() {
		return true;
	}

	

}
